import { PassportStrategy } from "@nestjs/passport";
import { Injectable, NotFoundException, UnauthorizedException } from "@nestjs/common";
import { Strategy } from "passport-local";
import { UserDao } from "../user.dao";

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy, "local") {

  constructor(
    private readonly userDao: UserDao
  ) {
    super();
  }

  /**
   * @Description: 用户校验
   * @author zhaojiuyi
   * @date 2023/4/9
   * @param {string} username 用户名
   * @param {string} password 密码
   * @return {Object} user
   */
  async validate(username: string, password: string) {
    const user = await this.userDao.getUserAllByName(username);
    if (!user) throw new NotFoundException("用户不存在");
    /* 判断密码是否正确 */
    if (password !== user.password) throw new UnauthorizedException("密码错误");
    /* 将Entity实体转换为普通对象 */
    return user;
  }
}
